<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 上方的警告框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类： </span>
          <!-- 选择分类的级联选择框 -->
          <el-cascader v-model="paramsCardKeys" :options="cardList" :props="cardListProps"
            expandTrigger='hover' @change="handleChange"></el-cascader>

          <!-- tab标签页 -->
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 添加动态参数的面板 -->
            <el-tab-pane label="动态参数" name="many">
              <!-- 添加属性的按钮 -->
              <el-button type="primary" @click="addDialogVisible=true" size="mini"
                :disabled="btnIsDisabled">添加参数</el-button>

              <!-- 动态数据表格区域 -->
              <el-table border stripe :data="manyTableDate">
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <div>
                      <!-- 标签行 -->
                      <el-tag @close="deleteTag(i,scope.row)" closable
                        v-for="(item,i ) in scope.row.attr_vals" :key="i">{{item}}
                      </el-tag>

                      <!-- 添加标签 -->
                      <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small"
                        @click="showInput(scope.row)">+ New
                        Tag</el-button>
                    </div>
                  </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">

                    <!-- 编辑按钮 -->
                    <el-button type="primary" @click="eaitDialogData(scope.row.attr_id)" size="mini"
                      icon="el-icon-edit">编辑</el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" @click="removeParmas(scope.row.attr_id)" size="mini"
                      icon="el-icon-delete">删除</el-button>

                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 添加静态属性的面板 -->
            <el-tab-pane label="静态属性" name="only">
              <!-- 添加属性的按钮 -->
              <el-button type="primary" @click="addDialogVisible=true" size="mini"
                :disabled="btnIsDisabled">添加属性</el-button>

              <!-- 静态属性表格区域 -->
              <el-table border stripe :data="onlyTableDate">
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <div>
                      <!-- 标签行 -->
                      <el-tag @close="deleteTag(i,scope.row)" closable
                        v-for="(item,i ) in scope.row.attr_vals" :key="i">{{item}}
                      </el-tag>

                      <!-- 添加标签 -->
                      <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small"
                        @click="showInput(scope.row)">+ New
                        Tag</el-button>
                    </div>
                  </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">

                    <!-- 编辑按钮 -->
                    <el-button type="primary" @click="eaitDialogData(scope.row.attr_id)" size="mini"
                      icon="el-icon-edit">编辑</el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" @click="removeParmas(scope.row.attr_id)" size="mini"
                      icon="el-icon-delete">删除</el-button>

                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

          </el-tabs>

        </el-col>
      </el-row>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+TitleName" :visible.sync="addDialogVisible" width="50%"
      @close="addDialogClosed">
      <!-- 添加参数的表单 -->
      <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px">
        <el-form-item :label="TitleName" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPramas">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+TitleName" :visible.sync="editDialogVisible" width="50%"
      @close="editDialogClosed">
      <!-- 添加参数的表单 -->
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="100px">
        <el-form-item :label="TitleName" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPramas">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cardList: [],
      // 级联选择框配置对象
      cardListProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定对象
      paramsCardKeys: [],
      // tab 标签选中的name名
      activeName: 'many',
      // 动态参数的数据
      manyTableDate: [],
      // 静态参数的数据
      onlyTableDate: [],
      // 控制添加参数对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addFrom: {
        attr_name: ''
      },
      // 添加参数的表单数据的验证对象
      addFromRules: {
        attr_name: [
          { required: true, message: '请输入你要添加的参数名称', trigger: 'blur' },
        ]
      },
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 修改参数的表单数据对象
      editFrom: {
        attr_name: ''
      },
      // 修改表单的表单数据的验证对象
      editFromRules: {
        attr_name: [
          { required: true, message: '请输入你要添加的参数名称', trigger: 'blur' },
        ]
      },

    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message('获取商品列表失败')
      }
      this.cardList = res.data
      // console.log(this.cardList);

    },
    // 监听级联选择框状态的改变
    handleChange () {

      // console.log(this.paramsCardKeys);
      this.paramsCaseList()
    },
    // tab 标签页的状态的改变
    handleTabClick () {
      // console.log(this.activeName);
      this.paramsCaseList()
    },
    // 获取参数列表的函数
    async paramsCaseList () {
      if (this.paramsCardKeys.length !== 3) {
        this.paramsCardKeys = []
        this.manyTableDate = []
        this.onlyTableDate = []
        return
      }
      // 获取参数列表
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制添加 tag 标签的输入框的显示与隐藏
        item.inputVisible = false
        // 绑定 输入框里的数据
        item.inputValue = ''
      })

      console.log(res.data);
      if (this.activeName === 'many') {
        this.manyTableDate = res.data
      } else {
        this.onlyTableDate = res.data
      }

    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFromRef.resetFields()
    },
    // 点击添加参数对话框 下的确定按钮的点击事件
    addPramas () {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addFrom.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.paramsCaseList()
        this.addDialogVisible = false
      })
    },
    // 监听修改对话框的关闭事件， 重置表单
    editDialogClosed () {
      this.$refs.editFromRef.resetFields();
    },
    // 点击修改按钮 的 修改对话框的显示  与获取分类
    async eaitDialogData (id) {

      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } })
      this.editFrom = res.data
      this.editDialogVisible = true

    },
    // 点击修改参数对话框 下的确定按钮的点击事件
    editPramas () {
      this.$refs.editFromRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editFrom.attr_id}`, {
          attr_name: this.editFrom.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改参数成功')
        this.paramsCaseList();
        this.editDialogVisible = false
      })
    },
    // 点击删除按钮 删除该参数
    async removeParmas (id) {
      const confirmResule = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResule !== 'confirm') {
        return this.$message.info('已取消删除操作')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('已成功删除该参数')
      this.paramsCaseList()
    },
    // 添加标签的 输入框的事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求将参数保存在后台服务器中
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加参数失败')
      this.$message.success('添加成功')

    },
    // 添加标签 按钮
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除 tag 标签
    async deleteTag (i, row) {
      row.attr_vals.splice(i, 1)
      // 发起请求将参数保存在后台服务器中
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除成功')
    }
  },
  computed: {
    // 如果级联选择器 返回的数组paramsCardKeys的长度小于3 则返回true禁用按钮  反之返回false 启用按钮
    btnIsDisabled () {
      if (this.paramsCardKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的Id
    cateId () {
      if (this.paramsCardKeys.length === 3) {
        return this.paramsCardKeys[2]
      }
      return null
    },
    TitleName () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>